// page/recentlyPlay/recentlyPlay.js
import request from "../../utils/request";

let innerAudioContext = null;
let pid = 0;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        historyRecords: [],
        playId: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let userData = wx.getStorageSync('userInfo')
        if (userData) {
            this.getPlayHistory(JSON.parse(userData).userId, 1)
        } else {
            wx.showToast({
                title: '请您先登录',
                icon: 'none'
            })
            wx.navigateTo({
                url: '/page/login/login'
            })
        }
    },
    // 根据id获取歌曲url
    async playSong(event) {
        let that = this;
        // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
        // 当前点击的时间
        let currentTime = event.timeStamp
        let lastTapTime = that.lastTapTime
        // 更新最后一次点击时间
        that.lastTapTime = currentTime
        // 如果两次点击时间在300毫秒内，则认为是双击事件
        if (currentTime - lastTapTime < 300) {
            if (event.currentTarget.id === pid && innerAudioContext != null && !innerAudioContext.paused) {
                innerAudioContext.pause();
            } else if (event.currentTarget.id === pid && innerAudioContext != null && innerAudioContext.paused) {
                innerAudioContext.play();
            } else {
                return;
            }
        } else {
            this.setData({
                playId: event.currentTarget.id
            })
            // 如果是当前歌曲
            if (event.currentTarget.id === pid) {
                return;
            } else if (innerAudioContext !== null) {
                innerAudioContext.stop();
                innerAudioContext.destroy();
            }
            pid = event.currentTarget.id
            let resultData = await request("/song/url", {id: pid})
            innerAudioContext = wx.createInnerAudioContext()
            innerAudioContext.src = resultData.data[0].url
            innerAudioContext.play()
        }
    },
    // 获取一周播放记录
    async getPlayHistory(uid, type) {
        let historyData = await request("/user/record", {uid: uid, type: type})
        this.setData({
            historyRecords: historyData.weekData,
        })
        let index = 0;
        this.data.historyRecords.id = index++;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
